<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import axios from 'axios'
import Navbar from '@/components/Navbar.vue'
import AcPanel from '@/components/AcPanel.vue'
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;  // 从环境变量获取基础 URL

const homeLinks = ref([
  {name: '分机管理', to: '/admin/sub'},
  {name: '中央配置', to: '/admin/center'}
]);

const rooms = ref();  // 现在我们从后端获取房间数据

const currentConfig = ref({
  AirCondition_num: 0,
  default_mode: 'cold',
  default_highest_temp: 25,
  default_lowest_temp: 18,
  default_tar_temp: 22,
  default_wind_level: 1,
  high_fee_rate: 1.5,
  middle_fee_rate: 1.0,
  low_fee_rate: 0.5,
  is_running: false
});

let fetchInterval;

onMounted(() => {
  const currentConfigTry = localStorage.getItem('currentConfig');
  console.log(currentConfigTry)
  if (currentConfigTry) {
    currentConfig.value = JSON.parse(currentConfigTry).currentConfig;
  }
  if(currentConfig.value.is_running) {
    fetchRooms();
    fetchInterval = setInterval(fetchRooms, 3000);  // 每3秒刷新一次
  }
});

onUnmounted(() => {
  clearInterval(fetchInterval);  // 组件卸载时清除定时器
});

async function fetchRooms() {
  try {
    const response = await axios.get(`${apiBaseUrl}/admin/sub/get_ac_state`);
    rooms.value = response.data.aircondition_state_data;  // 假设 aircondition_state_data 是我们需要的房间列表格式
  } catch (error) {
    console.error('Failed to fetch rooms:', error);
  }
}
</script>

<template>
  <div>
    <Navbar :links="homeLinks"/>
    <AcPanel :rooms="rooms"/>
  </div>
</template>

<style scoped>

</style>
